from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select

class Base:

    # 初始化驱动
    def __init__(self, driver):
        self.driver = driver
    # 封装打开网址
    def open_url(self,url):
        self.driver.get(url)
    # 封装查找元素
    def find_element(self,loc):
        # 异常处理
        try:
            WebDriverWait(self.driver,20,0.5).until(lambda driver: driver.find_element(*loc).is_displayed())
            return self.driver.find_element(*loc)
        except Exception as e:
            # 异常时截图
            self.driver.save_screenshot('error.png')
            print(e)
    # 封装点击
    def click(self,loc):
        self.find_element(loc).click()
    # 封装输入
    def send_keys(self,loc,info):
        self.find_element(loc).send_keys(info)
    # 封装滚动
    def scroll(self,x):
        self.driver.execute_script(f'window.scrollTo(0,{x})')
    # 封装alert弹窗处理
    def alert(self):
        self.driver.switch_to.alert.accept()
    # 封装iframe切换 进入
    def iframe(self,loc):
        self.driver.switch_to.frame(self.find_element(loc))
    # 封装iframe切换 退出
    def quit_iframe(self):
        self.driver.switch_to.default_content()
    # 封装窗口切换
    def new_window(self):
        self.driver.switch_to.window(self.driver.window_handles[-1])
    # 封装鼠标事件
    def action_click(self,loc):
        ActionChains(self.driver).click(self.find_element(loc)).perform()
    # 封装键盘事件
    def keys_enter(self,loc):
        self.find_element(loc).send_keys(Keys.ENTER)
    # 封装浏览器窗口操作
    def close(self):
        self.driver.close()
    # 封装下拉框选择
    def select(self,loc,x):
        select = Select(self.find_element(loc))
        select.select_by_value(x)